// components/authorize.js
const app = getApp()
let page = {}
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isShow: {
      type: Boolean,
      value: false
    },
    showFont: {
      type: String,
      value: '每日赚金币，优惠购好礼'
    },
    isRun: {
      type: Boolean,
      value: false
    }, 
  },

  /**
   * 组件的初始数据
   */
  data: {
    
  },

  /**
   * 组件的方法列表
   */
  methods: {
    getUserInfo() {
      let that = this
      let openid = wx.getStorageSync('openid')
      let sessionId = wx.getStorageSync("sessionid")
      if (!openid || !sessionId) {
        that.loginStep(that)
        return 
      } else {
        wx.getUserInfo({
          lang: "zh_CN",
          fail() {
          console.log('getUserInfo failed');
          setTimeout(function () {
            wx.showToast({
              title: '取消授权',
              icon: "none"
            });
            app.isAuth = false
            that.triggerEvent('authFail', false)
          }, 0);
          // THIS.setData({
          // 	rundatabutton: true
          // });
          },
          success: res => {
            wx.showLoading({
              title: '正在授权'
            })
            // app.isAuth = true
            const userInfo = res.userInfo;
            that.submitInfo(userInfo)
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            if (this.userInfoReadyCallback) {
              this.userInfoReadyCallback(res)
            }
          }
        })
      }
    },
    submitInfo(userInfo) {
      let that = this
      let openid = wx.getStorageSync('openid')
      let sessionId = wx.getStorageSync("sessionid")
      app.request(app.apiDomain + 'index.php?c=user&a=profile', {
        openid: openid,
        nickname: userInfo.nickName,
        gender: userInfo.gender,
        icon: userInfo.avatarUrl,
        invite_user: wx.getStorageSync('invite_user_user_id'),
        zone_name: userInfo.province + ' ' + userInfo.city,
      }, function (res) {
        if (res.data.status == 1) {
          wx.hideLoading()
          app.isAuth = true
          console.log('授权成功')
          that.triggerEvent('authSuccess')
        }
        app.setWxUserInfo(userInfo);
      }, 'POST')
    },
    loginStep: function (e) {
      var that = this;
      page = e
      wx.login({
        success(res) {
          if (res.code) {
            wx.request({
              url: app.apiDomain + 'index.php?c=user&a=getopenid',
              data: {
                code: res.code
              },
              success: function (res) {
                console.log('登录成功！')
                var user_info = res.data.data;
                wx.setStorageSync("openid", user_info.openid);
                if (res.data.data.star != null && !!res.data.data.star.hasOwnProperty('ji')) {
                  console.log(111)
                  if (!!res.data.data.star.hasOwnProperty('ji_1')) {
                    wx.setStorageSync("isGetChicken", '2')
                  } else if (!!res.data.data.star.hasOwnProperty('ji_2')) {
                    wx.setStorageSync("isGetChicken", '3')
                  } else {
                    wx.setStorageSync("isGetChicken", '1')
                  }

                } else {
                  wx.setStorageSync("isGetChicken", '')
                }
                var openid = user_info.openid;
                var cookie = res.header["Set-Cookie"];
                if (cookie != null) {
                  wx.setStorageSync("sessionid", res.header["Set-Cookie"]);
                }
                console.log(user_info, page)
                wx.setStorageSync('sex', user_info.sex)
                app.setApiUserInfo(user_info);
                //把数据写入Data
                app.setAppUserInfo(page)
                that.getUserInfo()
                // that.setWxUserInfo(user_info)
                //获取头像名字信息
                // that.userstat(THIS,openid);
                //获取步数
                // that.getRunData(openid, page);
              }
            })
          } else {
            console.log('登录失败！' + res.errMsg)
            return false
          }
        }
      });
    },
    cancle () {
      app.isAuth = false
      this.triggerEvent('authFail', false)
    },
    click() {
      console.log(111)
      this.triggerEvent('closeMask')
    },
    // 登录
    cancleStep () {
      this.triggerEvent('runFail', false)
    },
    run_auth () {
      let that = this
      wx.getWeRunData({
        fail(res) {
          app.isRun = false
          // 拒绝 微信运动
        },
        success(res) {
          // 微信运动授权成功
          app.isRun = true
          that.triggerEvent('runSuccess')
          // console.log(res,12)
          console.log('请求步数成功')
          // 运动挑战 定位授权
          wx.getSetting({
            success: function (resd) {
              let pages = getCurrentPages()
              if (pages[pages.length - 1].route.indexOf('play/index') != -1 || pages[pages.length - 1].route.indexOf('playIos/index') != -1 || pages[pages.length - 1].route.indexOf('playIos/index_ix') != -1) {
                if (!resd.authSetting['scope.userLocation']) {
                  wx.authorize({
                    scope: 'scope.userLocation',
                    success() {
                      wx.showToast({ //这里提示失败原因
                        title: '授权成功！',
                        duration: 1500
                      })
                    },
                    fail() {
                      wx.showToast({
                        title: '您还没有授权位置信息，可能会影响使用体验,可前往个人中心-授权管理开启授权',
                        icon: 'none'
                      });
                    }
                  })
                }
              }
            }
          })
          var encryptedData = res.encryptedData
          wx.request({
            url: app.apiDomain + 'index.php?c=user&a=getTodayStep',
            header: {
              //设置参数内容类型为x-www-form-urlencoded
              'content-type': 'application/x-www-form-urlencoded',
              'Accept': 'application/json'
            },
            data: {
              encryptedData: res.encryptedData,
              iv: res.iv,
              openid: wx.getStorageSync('openid')
            },
            method: "POST",
            success: function (res) {
              //判断是否第一次进来
              // if (res.data.data.login_num == "0") {
              //   THIS.setData({
              //     gif_on: 'on'
              //   })
              //   setTimeout(function (e = THIS) {
              //     e.setData({
              //       gif_on: ''
              //     })
              //   }, 6000);
              // }
              /**
               * 返回今日步数
               */
              var left_step = res.data.data.step - res.data.data.pointed_step;
              // console.log('执行成功0');
              //计算卡路里
              var t_num = (res.data.data.step / 20);
              var draw_point = res.data.data.draw_point;
              var step = res.data.data.step;
              // console.log(res,'步')
              let run_data = {
                tiao_num: t_num,
                tiao_ky: (t_num * 0.0065).toFixed(1),
                qian: draw_point ? draw_point : 0,
                todaystep: step ? step : 0,
                left_step: left_step ? left_step : 0
              }
              that.triggerEvent('setStep', run_data)
              // return true
            }
          })
        }
      });
    }
  }
})
